<?php

namespace App\Http\Controllers\Api\Meeting;

use App\Http\Controllers\Api\BaseController;
use App\Http\Controllers\Controller;
use App\Models\MeetingVolunteer;
use Illuminate\Http\Request;

class VolunteerController extends BaseController
{
    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function get(Request $request)
    {
        return ajaxReturn(['volunteer' => MeetingVolunteer::find($request->input('id'))]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function batchget(Request $request)
    {
        $query = MeetingVolunteer::query();
        return ajaxReturn([
            'total' => $query->count(),
            'items' => $query->offset($request->input('offset'))
                ->limit($request->input('count', 15))
                ->orderByDesc('id')->get()
        ]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function save(Request $request)
    {
        $volunteer = MeetingVolunteer::findOrNew($request->input('id'));
        $volunteer->fill($request->input('volunteer', []))->save();
        return ajaxReturn(['volunteer' => $volunteer]);
    }

    /**
     * @param Request $request
     * @return \Illuminate\Http\JsonResponse
     */
    public function signin(Request $request)
    {
        $name = $request->input('name');
        $tel = $request->input('tel');
        if ($volunteer = MeetingVolunteer::where(compact('name', 'tel'))->first()) {
            $signin = $volunteer->signins()->create([
                'longitude' => $request->input('longitude'),
                'latitude' => $request->input('latitude'),
                'address' => $request->input('address')
            ]);
            return ajaxReturn(['signin' => $signin]);
        } else {
            return ajaxError(404, '你输入的信息不存在');
        }
    }
}
